import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_ijkplayer/flutter_ijkplayer.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:zchope_student/utils/fluro.dart';
import 'package:zchope_student/utils/utils.dart';

import '../const.dart';
import 'playerdetail.dart';

class MyIjkPlayer extends StatefulWidget {
  final url;

  const MyIjkPlayer({Key key, this.url}) : super(key: key);

  @override
  _MyIjkPlayerState createState() => _MyIjkPlayerState();
}

class _MyIjkPlayerState extends State<MyIjkPlayer> {
  var controller = IjkMediaController();
  var dateStr;
  SharedPreferences sp;

//  var _studyMin = 0;
  var bindState = Const.UNSIGN;

  Orientation get orientation => MediaQuery.of(context).orientation;

  static const duration = const Duration(seconds: 1);

  int secondsPassed = 0;
  bool isActive = false;

  Timer timer;
  var durationText = '';

  handleTick() {
    if (isActive && controller.isPlaying&&bindState==Const.BIND) {
      print('Stream:${controller.isPlaying}');
      secondsPassed = secondsPassed + 1; //需要更新UI
      sp.setInt(Const.STUDY_MIN, secondsPassed);
      durationText = Utils.getInstance().formatDuration(secondsPassed);
      if (secondsPassed == 3600) {
        controller.pause();
        print('满两小时');
      }
      setState(() {

      });
    }
  }

  @override
  void initState() {
    super.initState();
    _convertDataSource(widget.url);
    _setData();
    Utils.getInstance().checkLogin().then((onValue) {
      bindState = onValue;
      if (bindState == Const.BIND) {
        durationText = Utils.getInstance().formatDuration(secondsPassed);
      } else {
        durationText = '未登录或未绑定,本次学习不计入学时';
      }
      setState(() {

      });
    });

  }

  _getStudyMin() async {
    sp = await SharedPreferences.getInstance();
    return sp.getInt(Const.STUDY_MIN);
  }

  _setData() async {
    secondsPassed = await _getStudyMin();
    isActive = true;
  }

  // 设置播放源
  _convertDataSource(String url) {
    var urls = FluroConvertUtils.fluroCnParamsDecode(url).split('/');
    String s = Uri.encodeComponent('${urls[5]}/${urls[6]}');
    DataSource source =
        DataSource.network('${urls[0]}//${urls[2]}/${urls[3]}/${urls[4]}/$s');
    controller.setDataSource(source, autoPlay: true);
  }

  @override
  void dispose() {
    controller.pauseOtherController();
    controller.dispose();
    isActive = false;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (timer == null) {
      timer = Timer.periodic(duration, (Timer t) {
        handleTick();
      });
    }


    return Scaffold(
      backgroundColor: Const.black,
      appBar: AppBar(
        title: Text(
          "视频播放",
        ),
      ),
      body: Column(
        children: <Widget>[
          _buildPlayerItem(),

          Padding(
            padding: const EdgeInsets.symmetric(vertical: 8),
            child: Text(
              durationText,
              style: TextStyle(color: Const.gold,fontSize: 14),
            ),
          ),
//
          Expanded(
            child: Message(),
          )
        ],
      ),
    );
  }

  _buildPlayerItem() {
    return Container(
      height: 200,
      child: IjkPlayer(
        mediaController: controller,
        controllerWidgetBuilder: (ctl) {
          return DefaultIJKControllerWidget(
              controller: ctl,
              doubleTapPlay: true,
              showFullScreenButton: true,
              hideSystemBarOnFullScreen: true);
        },
      ),
    );
  }

//  _buildMyIjkPlayerPlayer() {
//    var data = MediaQuery.of(context);
//    return Material(
//      child: Container(
//        width: data.size.width,
//        height: data.size.height,
//        child: IjkPlayer(
//          mediaController: controller,
//        ),
//      ),
//    );
//  }
}
